<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改店铺商品')"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: bootstrap-select-css"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: ztree-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-shop-product-edit" th:object="${shopProduct}">
        <input name="id" type="hidden" th:field="*{id}"/>
        <input id="productId" name="productId" type="hidden" th:field="*{productId}"/>
        <div class="form-group">
            <label class="col-sm-2 control-label "><span style="color: red; ">*</span>所属分类：</label>
            <div class="col-sm-8">
                <div id="categoryTrees" class="ztree"></div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>商品名称：</label>
            <div class="col-sm-6">
                <input class="form-control" type="text" th:field="*{productName}">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>商品类型：</label>
            <div class="col-sm-3">
                <div class="radio-box" th:each="dict : ${@dict.getType('product_type')}">
                    <input type="radio" th:id="${dict.dictCode}" th:value="${dict.dictValue}" th:field="*{productType}">
                    <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                </div>
            </div>
        </div>
        <div class="form-group" id="couponBox">
            <label class="col-sm-2 control-label">绑定优惠券：</label>
            <div class="col-sm-4">
                <select id="couponId" class="form-control select2-multiple" multiple>
                    <option th:each="one:${couponList}" th:value="${one.id}" th:text="${one.title}" th:selected="${one.selected}"></option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>兑换积分：</label>
            <div class="col-sm-4">
                <input class="form-control" type="number" min="1" th:field="*{productPrice}" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>库存：</label>
            <div class="col-sm-4">
                <input class="form-control" type="number" min="0" th:field="*{stock}" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>封面图：</label>
            <div class="col-sm-6">
                <input class="form-control" type="file" id="imageBtn" name="imageBtn" onchange="uploadImage(2)"/>
                <input class="form-control" name="coverUrl" id="imageUrl" type="hidden" th:value="*{coverUrl}">
                <span class="help-block m-b-none" style="color:red"><i class="fa fa-info-circle"></i>推荐尺寸：800*800</span>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>商品详情：</label>
            <div class="col-sm-8">
                <input id="memo" name="memo" type="hidden" th:field="*{memo}">
                <div id="editor" class="summernote"></div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>显示排序：</label>
            <div class="col-sm-4">
                <input class="form-control" type="number" th:field="*{orderNum}" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"><span style="color: red; ">*</span>状态：</label>
            <div class="col-sm-8">
                <div class="radio-box" th:each="dict : ${@dict.getType('product_status')}">
                    <input type="radio" th:id="${dict.dictCode}"  th:value="${dict.dictValue}" th:field="*{isEnable}">
                    <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                </div>
            </div>
        </div>
        <h4 class="form-header h4"></h4>
        <div class="row">
            <div class="col-sm-offset-2 col-sm-2">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i
                        class="fa fa-check"></i>保 存
                </button>
                </button>&nbsp;
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i
                        class="fa fa-reply-all"></i>关 闭
                </button>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: summernote-js"/>
<th:block th:include="include :: select2-js"/>
<th:block th:include="include :: bootstrap-select-js"/>
<th:block th:include="include :: ztree-js"/>

<script type="text/javascript">
    var prefix = ctx + "back/shopProduct";
    var initData = {
        coverUrl: $("#imageUrl").val()
    };
    var radioVal = $('input[name="productType"]:checked').val();
    if (radioVal == "0") {
        $("#couponBox").hide();
    } else if (radioVal == "1") {
        $("#couponBox").show();
    }

    $('input').on('ifChecked', function (event) {
        if ($(event.target).attr("name") == "productType") {
            var radio = $(event.target).val();
            if (radio == "0") {
                $("#couponBox").hide();
            } else if (radio == "1") {
                $("#couponBox").show();
            }
        }
    });

    $(function () {
        var url = ctx + "back/productCategory/treeData?systemModule=2&productId=" + $('#id').val();
        var options = {
            id: "categoryTrees",
            url: url,
            check: {enable: true},
            expandLevel: 0
        };
        $.tree.init(options);

        // 商品详情富文本初始化
        $('.summernote').summernote({
            placeholder: '请填写商品详情',
            height: 300,
            lang: 'zh-CN',
            dialogsInBody: true,
            callbacks: {
                //上传图片事件
                onImageUpload: function (files) {
                    ajaxUploadFile(function (result) {
                        if (result.code == web_status.SUCCESS) {
                            $('.summernote').summernote('editor.insertImage', result.url, result.fileName);
                        } else {
                            $.modal.alertError(result.msg);
                        }
                    }, files[0], 3)
                }
            }
        });
        var memo = $("#memo").val();
        $('.summernote').summernote('code', memo);
        $("#form-product-edit").validate({
            onkeyup: false,
            rules: {
                productName: {
                    remote: {
                        url: ctx + "back/product/checkProductNameUnique",
                        type: "post",
                        dataType: "json",
                        data: {
                            "productId": function () {
                                return $("#productId").val();
                            },
                            "productName": function () {
                                return $.common.trim($("#productName").val());
                            },
                        },
                        dataFilter: function (data, type) {
                            return $.validate.unique(data);
                        }
                    }
                },
                orderNum: {
                    digits: true
                }
            },
            messages: {
                "productName": {
                    remote: "商品已经存在"
                }
            },
            focusCleanup: true
        });

        //上传图片文件
        $("#imageBtn").fileinput({
            language: 'zh', //设置语言
            dropZoneTitle: '拖拽文件到这里 &hellip;<br>仅支持上传一张图片<br>多次上传替换前一张图片',
            allowedFileExtensions: ['jpg', 'png', 'bmp', 'jpeg'],//接收的文件后缀
            showUpload: false, //是否上传文件
            dropZoneEnabled: true,//是否显示拖拽区域
            initialPreview: '<img src="' + initData.coverUrl + '" class="file-preview-image" width="100%" height="auto" alt="商品封面图" title="商品封面图">',
            initialPreviewFileType: 'images',// 文件类型: 图片为images 其他为object
            maxFileCount: 1,
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
        }).on('fileclear', function (event, id) {
            $.modal.alertSuccess("删除图片成功！")
            $("#imageUrl").val('');
        });

        $('#couponId').select2({
            placeholder: "请选择兑换后赠送的优惠券",
            allowClear: true
        });

    });


    //通用上传文件
    function ajaxUploadFile(callback, file, modelType) {
        var formdata = new FormData();
        formdata.append("file", file);
        formdata.append("modelType", modelType);
        $.modal.loading("上传中...");
        $.ajax({
            url: ctx + "back/upload/image",
            data: formdata,
            type: "post",
            processData: false,
            contentType: false,
            success: function (result) {
                $.modal.closeLoading();
                callback(result);
            },
            error: function () {
                $.modal.closeLoading();
                $.modal.alertWarning("图片上传失败");
            }
        })
    }

    //图片文件上传
    function uploadImage(modelType) {
        var files = document.getElementById('imageBtn');
        if (files) {
            ajaxUploadFile(function (result) {
                if (result.code == 0) {
                    $.modal.alertSuccess("上传图片成功！")
                } else {
                    $.modal.alertError("上传图片失败，请重试");
                }
                $("#imageUrl").val(result.url);
            }, files.files[0], modelType);
        }
    }

    function submitHandler() {
        if ($.validate.form()) {
            var sHTML = $('.summernote').summernote('code');
            $("#memo").val(sHTML);
            let data = $('#form-shop-product-edit').serializeArray();
            var couponIdArr = $.form.selectSelects("couponId");
            data.push({"name": "couponIdArr", "value": couponIdArr});
            data.push({"name": "categoryIds", "value": $.tree.getCheckedNodes()});
            $.operate.saveTab(prefix + "/creditEdit", data);
        }
    }
</script>
</body>
</html>
